package cn.nawang.ebeim.api.comm;

import java.util.List;
import java.util.Map;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import cn.nawang.ebeim.api.utils.Constant;

/**
 * @ClassName: BaseQuery
 * @Description: TODO
 * @author 许炜毅
 * @date 2015年8月7日 上午8:34:21
 * @version v1.0
 */
@Repository
public class BaseQuery<T> {

  @Autowired
  private EntityManagerFactory entityManagerFactory;

  /**
   * @author 许炜毅
   * @Description 根据SQL语句，返回数据列表
   * @param sql
   * @return List<T>
   * @date 2015年8月7日下午3:14:44
   *
   * @修改人
   * @修改日期
   */
  public List<T> queryObject(String sql, Map<String, Object> paraMap) {
    EntityManager em = entityManagerFactory.createEntityManager();
    try {
      Query query = em.createQuery(sql);
      for (Map.Entry<String, Object> map : paraMap.entrySet()) {
        query.setParameter(map.getKey(), map.getValue());
      }
      List<T> list = query.getResultList();
      return list;
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      em.close();
    }
    return null;
  }

  /**
   * @author 许炜毅
   * @Description 根据传入的SQL语句，返回数据表中最大记录编号
   * @param sql
   * @return String
   * @date 2015年8月7日下午3:15:41
   *
   * @修改人
   * @修改日期
   */
  public String getMaxRecordId(String sql) {
    EntityManager em = entityManagerFactory.createEntityManager();
    try {
      Query query = em.createQuery(sql);
      query.setMaxResults(1);
      List lc = query.getResultList();
      if (lc == null || lc.isEmpty()) {
        return "1";
      } else {
        return String.valueOf(lc.get(0));
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      em.close();
    }
    return null;
  }

  /**
   * @author 许炜毅
   * @Description 查询统计
   * @param sql
   * @param em
   * @param sArray
   * @return int
   * @throws Exception
   * @date 2015年8月7日上午8:38:35
   *
   * @修改人
   * @修改日期
   */
  public int queryCount(String sql, Pages page) {
    EntityManager em = entityManagerFactory.createEntityManager();
    try {
      Query query = em.createQuery(sql);
      searchCondition(query, page.getSearchFormParams());
      List lc = query.getResultList();
      if (lc == null || lc.isEmpty()) {
        return 0;
      } else {
        return ((Long) lc.get(0)).intValue();
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    } finally {
      em.close();
    }
    return 0;
  }

  /**
   * @author 许炜毅
   * @Description 分页统计查询
   * @param sqlCount
   * @param sqlList
   * @param page
   * @return PageList<T>
   * @date 2015年8月7日上午9:18:41
   *
   * @修改人
   * @修改日期
   */
  public PageList queryListByPaging(String sqlCount, String sqlList, Pages page) {
    PageList pl = new PageList();
    EntityManager em = entityManagerFactory.createEntityManager();
    try {
      // 查询统计
      Query queryCount = em.createQuery(sqlCount);
      searchCondition(queryCount, page.getSearchFormParams());
      List lc = queryCount.getResultList();
      int count = 0;
      if (lc != null && !lc.isEmpty()) {
        count = ((Long) lc.get(0)).intValue();
      }
      page.setTotalPage(page.getAllPage(count));
      page.setTotalRecord(count);

      // 数据查询
      Query query = em.createQuery(sqlList);
      searchCondition(query, page.getSearchFormParams());
      query.setFirstResult(page.getStartPos());
      query.setMaxResults(page.getPageSize());
      List<T> list = query.getResultList();      
      pl.setObjList(list);
      pl.setPage(page);
      pl.setCode(Constant.CODE_SUCCESS);
      pl.setDesc("数据查询成功");
    } catch (Exception ex) {
      ex.printStackTrace();
      pl.setCode(Constant.CODE_ERROR);
      pl.setDesc("服务器忙，请稍后再试。");
    }finally{
      em.close();
    }
    return pl;
  }

  /**
   * @author 许炜毅
   * @Description 执行update、delete的SQL语句
   * @param sql
   * @return boolean
   * @date 2015年8月7日下午5:42:19
   *
   * @修改人
   * @修改日期
   */
  public boolean execHQL(String sql, Map<String, Object> paraMap) {
    EntityManager em = entityManagerFactory.createEntityManager();
    try {
      em.getTransaction().begin();
      Query query = em.createQuery(sql);
      for (Map.Entry<String, Object> item : paraMap.entrySet()) {
        query.setParameter(item.getKey(), item.getValue());
      }
      query.executeUpdate();
      em.getTransaction().commit();
      return true;
    } catch (Exception ex) {
      ex.printStackTrace();
    }finally{
      em.close();
    }
    return false;
  }

  /**
   * @author 许炜毅
   * @Description 组装查询条件
   * @param query
   * @param sArray
   * @return void
   * @date 2015年8月7日上午8:44:52
   *
   * @修改人
   * @修改日期
   */
  public void searchCondition(Query query, SearchFormParams[] sArray) {
    SearchFormParams sObj = null;
    if (sArray != null && sArray.length > 0) {
      for (int i = 0; i < sArray.length; i++) {
        sObj = (SearchFormParams) sArray[i];
        if (sObj.getType() == SearchFormParams.INTEGER_TYPE) {
          query.setParameter(sObj.getParam(), sObj.getValue());
        } else if (sObj.getType() == SearchFormParams.STRING_TYPE) {
          query.setParameter(sObj.getParam(), "%" + sObj.getValue() + "%");
        } else if (sObj.getType() == SearchFormParams.START_TIME_TYPE
            || sObj.getType() == SearchFormParams.END_TIME_TYPE) {
          query.setParameter(sObj.getParam(), sObj.getValue());
        }
        // else if (sObj.getType() == SearchFormParams.SELECT_IN_TYPE) {
        // query.setParameter(sObj.getParam(), sObj.getValue());
        // }
      }
    }
  }

  /**
   * @author 许炜毅
   * @Description 拼接查询条件
   * @param sArray
   * @return String
   * @date 2015年8月10日上午8:59:58
   *
   * @修改人
   * @修改日期
   */
  public String joinSearchCondition(Pages page) {
    SearchFormParams[] sArray = page.getSearchFormParams();
    SearchFormParams sObj = null;
    StringBuffer sb = new StringBuffer();
    if (sArray != null && sArray.length > 0) {
      for (int i = 0; i < sArray.length; i++) {
        sObj = (SearchFormParams) sArray[i];
        if (sObj.getType() == SearchFormParams.INTEGER_TYPE) {
          sb.append(" and " + sObj.getKey() + "=:" + sObj.getParam());
        } else if (sObj.getType() == SearchFormParams.STRING_TYPE) {
          sb.append(" and " + sObj.getKey() + " like :" + sObj.getParam());
        } else if (sObj.getType() == SearchFormParams.START_TIME_TYPE) {
          sb.append(" and " + sObj.getKey() + " >= :" + sObj.getParam());
        } else if (sObj.getType() == SearchFormParams.END_TIME_TYPE) {
          sb.append(" and " + sObj.getKey() + " <= :" + sObj.getParam());
        } else if (sObj.getType() == SearchFormParams.SELECT_IN_TYPE) {
          sb.append(" and " + sObj.getKey() + " in " + sObj.getValue());
        }
      }
    }
    return sb.toString();
  }

}
